package com.mla.fastdfs.utils;

import de.innosystec.unrar.Archive;
import com.mla.fastdfs.exception.ZipHypernumberException;
import com.mla.fastdfs.exception.ZipUnException;
import de.innosystec.unrar.exception.RarException;
import lombok.extern.slf4j.Slf4j;
import net.lingala.zip4j.core.ZipFile;
import net.lingala.zip4j.exception.ZipException;
import net.lingala.zip4j.model.FileHeader;
import net.lingala.zip4j.model.ZipParameters;
import net.lingala.zip4j.util.Zip4jConstants;
import net.sf.sevenzipjbinding.ExtractOperationResult;
import net.sf.sevenzipjbinding.IInArchive;
import net.sf.sevenzipjbinding.SevenZip;
import net.sf.sevenzipjbinding.impl.RandomAccessFileInStream;
import net.sf.sevenzipjbinding.simple.ISimpleInArchive;
import net.sf.sevenzipjbinding.simple.ISimpleInArchiveItem;
import org.apache.commons.io.IOUtils;
import org.springframework.util.StringUtils;

import java.io.*;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.concurrent.atomic.AtomicReference;

@Slf4j
public class ZipUtils {
    public static final String compress = ".zip,.rar,.7z,.tar";

    /**
     * 根据给定密码压缩文件(s)到指定目录
     *
     * @param destFileName 压缩文件存放绝对路径 e.g.:D:/upload/zip/demo.zip
     * @param passwd       密码(可为空)
     * @param files        单个文件或文件数组
     * @return 最终的压缩文件存放的绝对路径, 如果为null则说明压缩失败.
     */
    public static String compress(String destFileName, String passwd, File... files) {
        ZipParameters parameters = new ZipParameters();
        parameters.setCompressionMethod(Zip4jConstants.COMP_DEFLATE); // 压缩方式
        parameters.setCompressionLevel(Zip4jConstants.DEFLATE_LEVEL_NORMAL); // 压缩级别
        if (!StringUtils.isEmpty(passwd)) {
            parameters.setEncryptFiles(true);
            parameters.setEncryptionMethod(Zip4jConstants.ENC_METHOD_STANDARD); // 加密方式
            parameters.setPassword(passwd.toCharArray());
        }
        try {
            ZipFile zipFile = new ZipFile(destFileName);
            for (File file : files) {
                zipFile.addFile(file, parameters);
            }
            return destFileName;
        } catch (ZipException e) {
            e.printStackTrace();
        }

        return null;
    }

    /**
     * 根据给定密码压缩文件(s)到指定位置
     *
     * @param destFileName 压缩文件存放绝对路径 e.g.:D:/upload/zip/demo.zip
     * @param passwd       密码(可为空)
     * @param filePaths    单个文件路径或文件路径数组
     * @return 最终的压缩文件存放的绝对路径, 如果为null则说明压缩失败.
     */
    public static String compress(String destFileName, String passwd, String... filePaths) {
        int size = filePaths.length;
        File[] files = new File[size];
        for (int i = 0; i < size; i++) {
            files[i] = new File(filePaths[i]);
        }
        return compress(destFileName, passwd, files);
    }

    /**
     * 根据给定密码压缩文件(s)到指定位置
     *
     * @param destFileName 压缩文件存放绝对路径 e.g.:D:/upload/zip/demo.zip
     * @param passwd       密码(可为空)
     * @param folder       文件夹路径
     * @return 最终的压缩文件存放的绝对路径, 如果为null则说明压缩失败.
     */
    public static String compressFolder(String destFileName, String passwd, String folder) {
        File folderParam = new File(folder);
        if (folderParam.isDirectory()) {
            File[] files = folderParam.listFiles();
            return compress(destFileName, passwd, files);
        }
        return null;
    }

    /**
     * 根据所给密码解压zip压缩包到指定目录
     * <p>
     * 如果指定目录不存在,可以自动创建,不合法的路径将导致异常被抛出
     *
     * @param zipFile zip压缩包绝对路径
     * @param dest    指定解压文件夹位置
     * @param passwd  密码(可为空)
     * @return 解压后的文件数组
     * @throws ZipException
     */
    @SuppressWarnings("unchecked")
    public static File[] deCompress(File zipFile, String dest, String passwd) throws ZipException {
        //1.判断指定目录是否存在
        File destDir = new File(dest);
        if (destDir.isDirectory() && !destDir.exists()) {
            destDir.mkdir();
        }
        //2.初始化zip工具
        ZipFile zFile = new ZipFile(zipFile);
        zFile.setFileNameCharset("UTF-8");
        if (!zFile.isValidZipFile()) {
            throw new ZipException("压缩文件不合法,可能被损坏.");
        }
        //3.判断是否已加密
        if (zFile.isEncrypted()) {
            zFile.setPassword(passwd.toCharArray());
        }
        //4.解压所有文件
        zFile.extractAll(dest);
        List<FileHeader> headerList = zFile.getFileHeaders();
        List<File> extractedFileList = new ArrayList<File>();
        for (FileHeader fileHeader : headerList) {
            if (!fileHeader.isDirectory()) {
                extractedFileList.add(new File(destDir, fileHeader.getFileName()));
            }
        }
        File[] extractedFiles = new File[extractedFileList.size()];
        extractedFileList.toArray(extractedFiles);
        return extractedFiles;
    }

    /**
     * 解压无密码的zip压缩包到指定目录
     *
     * @param zipFile zip压缩包
     * @param dest    指定解压文件夹位置
     * @return 解压后的文件数组
     * @throws ZipException
     */
    public static File[] deCompress(File zipFile, String dest) {
        try {
            return deCompress(zipFile, dest, null);
        } catch (ZipException e) {
            e.printStackTrace();
        }
        return null;
    }

    /**
     * 根据所给密码解压zip压缩包到指定目录
     *
     * @param zipFilePath zip压缩包绝对路径
     * @param dest        指定解压文件夹位置
     * @param passwd      压缩包密码
     * @return 解压后的所有文件数组
     */
    public static File[] deCompress(String zipFilePath, String dest, String passwd) {
        try {
            return deCompress(new File(zipFilePath), dest, passwd);
        } catch (ZipException e) {
            if (e.getMessage().contains("Wrong Password for file")) {

            }
            e.printStackTrace();
        }
        return null;
    }

    /**
     * 无密码解压压缩包到指定目录
     *
     * @param zipFilePath zip压缩包绝对路径
     * @param dest        指定解压文件夹位置
     * @return 解压后的所有文件数组
     */
    public static File[] deCompress(String zipFilePath, String dest) {
        try {
            return deCompress(new File(zipFilePath), dest, null);
        } catch (ZipException e) {
            e.printStackTrace();
        }
        return null;
    }

    /**
     * 支持 zip,rar4,7z,tar
     *
     * @param file7zPath(7z文件路径)
     * @param outPutPath(解压路径)
     * @param passWord(文件密码.没有可随便写,或空)
     * @return
     * @throws Exception
     * @Description (解压7z)
     */
    public static String un7z(String file7zPath, final String outPutPath, String passWord) throws Exception {
        AtomicReference<String> filePath = new AtomicReference<>();
        RandomAccessFile randomAccessFile;
        randomAccessFile = new RandomAccessFile(file7zPath, "r");
        IInArchive archive = SevenZip.openInArchive(null, new RandomAccessFileInStream(randomAccessFile), passWord);
        int numberOfItems = archive.getNumberOfItems();
        if (numberOfItems != 1) {
            throw new ZipHypernumberException(archive.getNumberOfItems() + "");
        }
        ISimpleInArchive simpleInArchive = archive.getSimpleInterface();
        for (final ISimpleInArchiveItem item : simpleInArchive.getArchiveItems()) {
            final int[] hash = new int[]{0};
            if (!item.isFolder()) {
                ExtractOperationResult result;
                final long[] sizeArray = new long[1];
                result = item.extractSlow(data -> {
                    FileOutputStream out = null;
                    try {
                        //判断压缩包内的文件是否存在
                        int endNum = item.getPath().lastIndexOf(File.separator);
                        if (endNum < 1) endNum = item.getPath().lastIndexOf("/");
                        if (endNum < 1) endNum = 0;
                        String parentFilePath = outPutPath + File.separator + item.getPath().substring(0, endNum);
                        if (!new File(parentFilePath).exists()) {
                            new File(parentFilePath).mkdirs();
                        }
                        filePath.set(outPutPath + File.separator + item.getPath());
                        out = new FileOutputStream(new File(filePath.get()), true);
                        IOUtils.write(data, out);
                    } catch (Exception e) {
                        log.error(e.getMessage(), e);
                    } finally {
                        try {
                            out.close();
                        } catch (IOException e) {
                        }
                    }
                    hash[0] ^= Arrays.hashCode(data); // Consume data
                    sizeArray[0] += data.length;
                    return data.length; // Return amount of consumed
                }, passWord);
                if (result != ExtractOperationResult.OK) {
                    throw new ZipUnException();
                }
            }
        }
        archive.close();
        randomAccessFile.close();
        return filePath.get();
    }

    /**
     * 解压指定的RAR压缩文件到指定的目录中
     *
     * @param srcRar   指定的RAR压缩文件
     * @param destPath 指定解压到的目录
     * @param password 压缩文件时设定的密码
     * @throws IOException
     */
    public static void unrar(String srcRar, String destPath, String password) throws IOException {
        File srcFile = new File(srcRar);
        if (!srcFile.exists()) {
            return;
        }
        if (null == destPath || destPath.length() == 0) {
            unrar(srcFile, srcFile.getParent(), password);
            return;
        }
        unrar(srcFile, destPath, password);
    }

    /**
     * 解压指定RAR文件到指定的路径
     *
     * @param srcRarFile 需要解压RAR文件
     * @param destPath   指定解压路径
     * @param password   压缩文件时设定的密码
     * @throws IOException
     */
    public static void unrar(File srcRarFile, String destPath, String password) throws IOException {
        if (null == srcRarFile || !srcRarFile.exists()) {
            throw new IOException("指定压缩文件不存在.");
        }
        if (!destPath.endsWith(File.separator)) {
            destPath += File.separator;
        }
        Archive archive = null;
        OutputStream unOut = null;
        try {
            archive = new Archive(srcRarFile, password, false);
            de.innosystec.unrar.rarfile.FileHeader fileHeader = archive.nextFileHeader();
            while (null != fileHeader) {
                if (!fileHeader.isDirectory()) {
                    // 1 根据不同的操作系统拿到相应的 destDirName 和 destFileName
                    String destFileName = "";
                    String destDirName = "";
                    if (File.separator.equals("/")) {        // 非windows系统
                        destFileName = (destPath + fileHeader.getFileNameW()).replaceAll("\\\\", "/");
                        destDirName = destFileName.substring(0, destFileName.lastIndexOf("/"));
                    } else {        // windows系统
                        destFileName = (destPath + fileHeader.getFileNameW()).replaceAll("/", "\\\\");
                        destDirName = destFileName.substring(0, destFileName.lastIndexOf("\\"));
                    }
                    // 2创建文件夹
                    File dir = new File(destDirName);
                    if (!dir.exists() || !dir.isDirectory()) {
                        dir.mkdirs();
                    }
                    // 抽取压缩文件
                    unOut = new FileOutputStream(new File(destFileName));
                    archive.extractFile(fileHeader, unOut);
                    unOut.flush();
                    unOut.close();
                }
                fileHeader = archive.nextFileHeader();
            }
            archive.close();
        } catch (RarException e) {
            e.printStackTrace();
        } finally {
            IOUtils.closeQuietly(unOut);
        }
    }

    public static void main(String[] args) throws Exception {
//        String folder = "D:\\upload\\backup\\down\\dezip\\";
//        compress("D:/upload/zip/测试.zip", "123456", folder);
        // System.out.println("D:/祖国山河03.7z".lastIndexOf(File.pathSeparator));
       /* String str="D:/祖国山河03.7z";
        int endNum = str.lastIndexOf(File.separator);
        if (endNum < 1) endNum = str.lastIndexOf("/");
        String parentFilePath = "D:/祖国山河03" + str.substring(endNum);
        System.out.println(parentFilePath);*/
        unrar("D:/祖国山河01.rar", "D:/祖国山河01", "123456");
        // File[] files = deCompress("D:/祖国山河03.7z", "D:/祖国山河03", "123456");
       /* for (File file : files) {
            System.out.println(file.getPath());
        }*/

       /* try {
            UnrarCallback callback=new U
            Archive a=new Archive(new File("D:/祖国山河01.rar"),"123465");

        } catch (RarException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }*/
        // System.out.println(System.getProperty("user.dir").replace("\\", "/"));
    }
}